package com.cheche.dn.common;

import com.cheche.dn.utils.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Util - Id生成策略
 * Created by cheshun on 15/7/28.
 */
public final class IdWorker {

    private static final Logger logger = LoggerFactory.getLogger(IdWorker.class);

    public static final IdWorker INSTANCE;

    static {
        INSTANCE = new IdWorker(
                PropertiesUtil.getPropertiesLong("worker.id"),
                PropertiesUtil.getPropertiesLong("datacenter.id")
        );
    }

    private long sequence = 0L;
    private long lastTimestamp = -1L;

    private final long workerId;
    private final long datacenterId;

    private static final long twepoch = 1438093550745L;

    private static final long workerIdBits = 5L;
    private static final long maxWorkerId = ~(-1L << workerIdBits);

    private static final long datacenterIdBits = 5L;
    private static final long maxDatacenterId = ~(-1L << datacenterIdBits);

    private static final long sequenceBits = 12L;
    private static final long workerIdShift = sequenceBits;
    private static final long datacenterIdShift = sequenceBits + workerIdBits;
    private static final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    private static final long sequenceMask = ~(-1L << sequenceBits);

    public IdWorker(final long workerId, final long datacenterId) {
        super();
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format(
                    "worker Id can't be greater than %d or less than 0",
                    maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format(
                    "datacenter Id can't be greater than %d or less than 0",
                    maxWorkerId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    public synchronized long nextId() {
        long timestamp = this.timeGen();

        if (timestamp < this.lastTimestamp) {
            try {
                logger.error(String.format("clock is moving backwards. Rejecting requests until %d.", lastTimestamp));
                throw new Exception(
                        String.format(
                                "Clock moved backwards.  Refusing to generate id for %d milliseconds",
                                this.lastTimestamp - timestamp));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (this.lastTimestamp == timestamp) {
            this.sequence = (this.sequence + 1) & sequenceMask;
            if (this.sequence == 0) {
                timestamp = this.tilNextMillis(this.lastTimestamp);
            }
        } else {
            this.sequence = 0;
        }

        this.lastTimestamp = timestamp;
        long nextId = ((timestamp - twepoch) << timestampLeftShift)
                | (this.datacenterId << datacenterIdShift)
                | (this.workerId << workerIdShift) | (this.sequence);
        logger.info(String.format("worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, datacenter id %d, worker id %d",
                timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, datacenterId, workerId));
        return nextId;
    }

    private long tilNextMillis(final long lastTimestamp) {
        long timestamp = this.timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = this.timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }

}
